package com.steakliu.gateway.builder;

import com.steakliu.gateway.definition.GateWayPredicateDefinition;
import com.steakliu.gateway.definition.GatewayFilterDefinition;
import com.steakliu.gateway.definition.GatewayRouteDefinition;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.handler.predicate.PredicateDefinition;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

public class RouteDefinitionBuilder {
    public static RouteDefinition trans(GatewayRouteDefinition gatewayRouteDefinition){
        RouteDefinition definition = new RouteDefinition();
        definition.setId(gatewayRouteDefinition.getRouteId());
        definition.setOrder(gatewayRouteDefinition.getOrder());

        List<PredicateDefinition> predicateDefinitionList = new ArrayList<>();
        List<GateWayPredicateDefinition> gateWayPredicateDefinitionList = gatewayRouteDefinition.getPredicates();

        for (GateWayPredicateDefinition gateWayPredicateDefinition : gateWayPredicateDefinitionList){
            PredicateDefinition predicateDefinition = new PredicateDefinition();
            predicateDefinition.setArgs(gateWayPredicateDefinition.getArgs());
            predicateDefinition.setName(gateWayPredicateDefinition.getName());
            predicateDefinitionList.add(predicateDefinition);
        }
        definition.setPredicates(predicateDefinitionList);

        List<FilterDefinition> filters = new ArrayList<>();
        List<GatewayFilterDefinition> gatewayFilters = gatewayRouteDefinition.getFilters();
        for (GatewayFilterDefinition filterDefinition : gatewayFilters){
            FilterDefinition filter = new FilterDefinition();
            filter.setName(filterDefinition.getName());
            filter.setArgs(filterDefinition.getArgs());
            filters.add(filter);
        }
        definition.setFilters(filters);

        URI uri = null;
        if (gatewayRouteDefinition.getUri().startsWith("http")){
            uri = UriComponentsBuilder.fromHttpUrl(gatewayRouteDefinition.getUri()).build().toUri();
        }else {
            uri = URI.create(gatewayRouteDefinition.getUri());
        }
        definition.setUri(uri);
        return definition;
    }
}
